package com.gmrz.uap.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by gongyuqiang on 2017/5/8.
 */
public class HttpClientUtil {

    public static String post(String postUrl, String data, String contentType){
        HttpURLConnection conn = null;
        OutputStream out = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(postUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Charset", "UTF-8");
            // 设置文件类型:
            conn.setRequestProperty("Content-Type", contentType);
            conn.connect();
            out = conn.getOutputStream();
            // 写入请求的字符串
            out.write(data.getBytes());
            out.flush();
            inputStream = conn.getInputStream();
            if (conn.getResponseCode() == 200) {
                // 请求返回的数据
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String str = null;
                StringBuffer buffer = new StringBuffer();
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                }
                //释放资源
                bufferedReader.close();
                inputStreamReader.close();

                return buffer.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            close(out);
            close(inputStream);
            if (conn != null) {
                conn.disconnect();
            }
        }
        throw new RuntimeException("server response failed");
    }

    private static void close(OutputStream out){
        if (null != out) {
            try {
                out.close();
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage());
            }
        }
    }

    private static void close(InputStream in){
        if (null != in) {
            try {
                in.close();
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage());
            }
        }
    }

}
